package cn.trda.controller;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import cn.trda.pojo.Function;
import cn.trda.pojo.User;
import cn.trda.pojo.EasyUITreeNode;
import cn.trda.service.FunctionService;

@Controller
@RequestMapping("main/")
public class MainController extends BaseController {
	@Autowired
	private FunctionService functionService;
	
	@RequestMapping(value="tree")
	public @ResponseBody Object tree(HttpSession session) throws Exception{
		User user = this.getSessionUser(session);
		List<Function> functions = functionService.getFunctionByRoleId(user.getRoleid());
		//返回的对象集合	
		List<EasyUITreeNode> tree = new ArrayList<EasyUITreeNode>();	
		functionsToEasyuiTreeNodes(0L,functions,tree);
		return tree;
	}
	
	//加载指定的parentid的下面的所有子节点
	private void functionsToEasyuiTreeNodes(Long parentid,List<Function> functions,List<EasyUITreeNode> tree){
		for(int i=0; i<functions.size();i++){
			//System.out.println((long)functions.get(i).getParentid()==(parentid));
			if((long)functions.get(i).getParentid()==(parentid)){
				
				EasyUITreeNode node = functionToEasyuiTreeNode(functions.get(i));
				//递归调用
				
				functionsToEasyuiTreeNodes(functions.get(i).getId(),functions,node.getChildren());
				//添加到集合中
				tree.add(node);
			}
		}	
	}
	//对象转换
	private EasyUITreeNode functionToEasyuiTreeNode(Function function) {
		EasyUITreeNode node = new EasyUITreeNode();
		node.setText(function.getFunctionname());
		Map<String,Object> attributes = new HashMap<String,Object>();
		attributes.put("url", function.getFuncurl());
		node.setAttributes(attributes);
		return node;
	}
}
